package cn.wing.event;

import cn.wing.gui.TradingMenu;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class OpenSharedMenuPacket {

    private Boolean sub = false;

    private int num = 0;

    public OpenSharedMenuPacket() {}

    public OpenSharedMenuPacket(Boolean sub, int num) {
        this.sub = sub;
        this.num = num;
    }

    public static void encode(OpenSharedMenuPacket msg, FriendlyByteBuf buf) {
        buf.writeBoolean(msg.sub);
        buf.writeInt(msg.num);
    }

    public static OpenSharedMenuPacket decode(FriendlyByteBuf buf) {
        return new OpenSharedMenuPacket(buf.readBoolean(), buf.readInt());
    }

    public static void handle(OpenSharedMenuPacket msg, Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        context.enqueueWork(() -> {

            // 客户端发送发开menu请求
            ServerPlayer player = context.getSender();

            if (player != null && !msg.sub) {
                // open menu
                player.openMenu(new SimpleMenuProvider(
                        (id, inv, p) -> new TradingMenu(id, inv),
                        Component.translatable("itemPay")
                ));
            }

            // sub item to sellMap
            if (player != null && msg.sub) {
                TradingMenu tradingMenu = (TradingMenu) player.containerMenu;
                tradingMenu.sell(msg.num, player.getUUID());
            }
        });
        context.setPacketHandled(true);
    }
}